package com.intretech.umsin.common.excel.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @version V1.0
 * @ClassName: LocalDateTimeConverter
 * @Description: LocalDateTimeConverter 服务实现
 * @author: 李启联
 * @date: 2022-5-28 11:38
 * @Copyright: Copyright (c) 2022
 */
public class LocalDateTimeConverter implements Converter<LocalDateTime> {

    @Override
    public Class supportJavaTypeKey() {
        return LocalDateTime.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public LocalDateTime convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        String patternStr = "yyyy-MM-dd HH:mm:ss";
        if(!ObjectUtils.isEmpty(excelContentProperty.getDateTimeFormatProperty()) && !StringUtils.isEmpty(excelContentProperty.getDateTimeFormatProperty().getFormat())){
            patternStr  = excelContentProperty.getDateTimeFormatProperty().getFormat();
        }
        return LocalDateTime.parse(cellData.getStringValue(), DateTimeFormatter.ofPattern(patternStr));
    }

    @Override
    public CellData convertToExcelData(LocalDateTime localDateTime, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        String patternStr = "yyyy-MM-dd HH:mm:ss";
        if(!ObjectUtils.isEmpty(excelContentProperty.getDateTimeFormatProperty()) && !StringUtils.isEmpty(excelContentProperty.getDateTimeFormatProperty().getFormat())){
            patternStr  = excelContentProperty.getDateTimeFormatProperty().getFormat();
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(patternStr);
        String format = formatter.format(localDateTime);
        return new CellData(format);
    }
}

